<?php
/**
 * 阿里云图片上传工具类
 */

namespace App\Commons\Utils;


use App\Commons\Exceptions\AliyunCsException;
use Illuminate\Support\Facades\Log;
use OSS\Core\OssException;
use OSS\OssClient;

class AliYunCsTool {

    /**
     * 图片前缀文件夹定义
     */
    const OBJECT_PREFIX_COM = 'merchant-wechat-mini-program/';//通用

    private $_accessKeyId;
    private $_accessKeySecret;
    private $_endpoint;

    private $_ossClient;

    /**
     * AliYunCsTool constructor.
     *
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @param string $endpoint
     *
     * @throws OssException
     */
    public function __construct($accessKeyId = null, $accessKeySecret = null, $endpoint = null) {
        $this->_accessKeyId     = $accessKeyId ?: config('alioss.accessKeyId');
        $this->_accessKeySecret = $accessKeySecret ?: config('alioss.accessKeySecret');
        $this->_endpoint        = $endpoint ?: config('alioss.endpoint');

        try {
            $this->_ossClient = new OssClient($this->_accessKeyId, $this->_accessKeySecret, $this->_endpoint);
        } catch (OssException $e) {
            Log::error($e->getMessage());
            throw $e;
        }
    }

    /**
     * 上传图片
     *
     * @param $fileTmp
     * @param $fileName
     * @param string $objectPrefix
     * @param null $bucket
     * @return null
     * @throws AliyunCsException
     */
    public function uploadFile($fileTmp, $fileName, $objectPrefix = self::OBJECT_PREFIX_COM, $bucket = null) {
        $bucket = $bucket ?: config('alioss.bucket');
        try {
            $result = $this->_ossClient->uploadFile($bucket, $objectPrefix . $fileName, $fileTmp);
        } catch (OssException $e) {
            Log::error($e->getMessage());
            throw new AliyunCsException(1010001);
        }

        return $result;
    }

    /**
     * 获取随机文件名
     * @return string
     */
    public static function getRandomFileName() {
        $fineTime = str_pad((string)array_sum(explode(" ", microtime())), 19, 0);

        return md5($fineTime . str_random(32));
    }

    /**
     * 常规上传
     *
     * @param \Illuminate\Http\UploadedFile|\Illuminate\Http\UploadedFile[]|array|null $imgFile 通过$request->file('file');获取的
     * @param null $uploadImgName
     * @param string $objectPrefix
     * @param null $bucket
     * @return null
     * @throws OssException
     */
    public static function commonUpload($imgFile, $uploadImgName = null, $objectPrefix = self::OBJECT_PREFIX_COM, $bucket = null) {
        $upResult = null;
        if ($imgFile) {
            $fileTmp = $imgFile->getRealPath();

            if (!$uploadImgName) {
                $fileExtension       = $imgFile->getClientOriginalExtension();
                $originNameExtension = $fileExtension ? ('.' . $fileExtension) : '';
                $uploadImgName       = AliYunCsTool::getRandomFileName() . $originNameExtension;
            }

            $aliYunCssTool = new static();
            $upResult      = $aliYunCssTool->uploadFile($fileTmp, $uploadImgName, $objectPrefix, $bucket);

            if (isset($upResult['oss-request-url'])) {
                $upResult['fileUrl']  = $upResult['oss-request-url'];
                $upResult['fileName'] = $uploadImgName;
            }
        }

        return $upResult;
    }
}